import axios from 'axios'
import domMessage from './messageOnce'
const messageOnce = new domMessage()
import store from '../store'
import { getToken,removeToken } from '@/utils/auth'
import { Loading } from 'element-ui'
import router from '../router'
let loadingInstance

// let baseURL = 'https://chenmouren.asia'
// let baseURL = 'https://flyingparcel.ca'
let baseURL = location.protocol+'//'+location.host
let needLoadingRequestCount = 0

let loading

function startLoading() {
  loading = Loading.service({
    lock: true,
    background: '#eff3f6'
  })
}

function endLoading() {
  loading.close()
}

 function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}

 function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}

// 创建axios实例
const service = axios.create({
  baseURL, // api 的 base_url
  timeout: 100000, // 请求超时时间,
  withCredentials: true
})

// request拦截器
service.interceptors.request.use(
  config => {
    if (!config.headers['No-Request-Loading']) {
      showFullScreenLoading()
    }
    if(localStorage.storeId){
      config.headers['storeId'] = localStorage.storeId
      config.headers['storeName'] = encodeURIComponent(localStorage.storeName)
    }
    if(getToken()){
      config.headers['authToken'] = getToken()
    }
    return config
  },
  error => {
    tryHideFullScreenLoading()
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    tryHideFullScreenLoading()
    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = response.data
    if (res.code !== 200) {
      messageOnce.error({
        message: res.msg || '服务端发生未知错误！',
        duration: 5 * 1000
      })
      return Promise.reject(res)
    } else {
      return response.data
    }
  },
  error => {
    tryHideFullScreenLoading()
    let message = error.message.indexOf('timeout')!==-1?'服务器连接超时，请重试！': '服务端发生未知错误！'
    if(error.response && error.response.status === 403){
      message = '没有访问权限！'
    }
    if(error.response && error.response.status === 401){
      message = '请先登录后在访问！'
      store.dispatch('FedLogOut').then(()=>{
        router.push('/login?redirect='+location.hash.slice(1))
      })
    }
    messageOnce.error({
      message,
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default {
  request:service,
  baseURL
}
